#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tp3.h"



  void fileseek(FILE *arq, int steps, int tamsk){
    if(tamsk==200){
      fseek(arq,steps*450,0);
    }
    if(tamsk==100){
      fseek(arq,(steps*450)+200,0);
    }
    if(tamsk==125){
      fseek(arq,(steps*450)+300,0);
    }
    if(tamsk==4){
      fseek(arq,(steps*450)+425,0);
    }
  }

  PK* CarregaSKDaBase(int *nu, int *nulista, FILE *base, int tamsk, FILE *listainvertida){
    int i=0,a=0,b=0,nsk=0,nlista=0, a1=0, NRRwrt;
    char buffer[200],verifica[200], titulowrt[200];
    PK *found,*listask;
    listask=(PK*)malloc(20*sizeof(PK));
    while(fgets(buffer,tamsk,base)!=NULL){
      fileseek(base,i,tamsk);
      fread(buffer,1,tamsk,base);
	  for(a=tamsk;a<200;a++){
	    buffer[a]=' ';
	  }
	  a=0;
      fileseek(base,i,200);
	  fread(titulowrt,1,tmtitulo,base);
      while((buffer[a]!=' ')&&(a<tamsk)){
	    while((buffer[a]!=' ')&&(a<tamsk)){
          verifica[a1]=buffer[a];
          a++;
          a1++;
        }
        b=a1;
        a++;
        a1=0;
        while(b<200){
	  verifica[b]=' ';
          b++;
        }
        if(nsk>0){
	  found=BSearch(listask,verifica,0,nsk-1);
	}
        else{
          found=NULL;
        }
        if(found==NULL){
          NRRwrt=-1;
          fseek(listainvertida,nlista*204,0);
          fwrite(titulowrt,1,tmtitulo,listainvertida);
          fwrite(&NRRwrt,1,4,listainvertida);
	  nlista++;
          nsk++;
          for(b=0;b<200;b++){
            listask[nsk-1].titulo[b]=verifica[b];
          }
          listask[nsk-1].NRR=nlista-1;
          if(nsk%20==0){
            listask=(PK*)realloc(listask,(nsk+20)*sizeof(PK));
          }
          Ordena(listask,0,nsk-1);
	}
        else{
	  NRRwrt=found->NRR;
	  fseek(listainvertida,nlista*204,0);
 	  fwrite(titulowrt,1,tmtitulo,listainvertida);
 	  fwrite(&NRRwrt,1,4,listainvertida);
          found->NRR=nlista;
	  nlista++;
  	}
      }
      b=0;
      i++;
      a=0;
      fseek(base,i*450,0);
    }
    *nu=nsk;
    *nulista=nlista;
    return listask;
  }

  PK* CarregaSK(FILE *SKlist, int *nSK){
    int n, NRR, i=0;
    char buffer[200];
    PK *list;
    list=(PK*)malloc(20*sizeof(PK));
    fread(&n,1,4,SKlist);
    while(feof(SKlist)==0){
      fread(buffer,1,n,SKlist);
      while(n<200){
        buffer[n]=' ';
        n++;
      }
      fread(&NRR,1,4,SKlist);
      for(n=0;n<200;n++){
        list[i].titulo[n]=buffer[n];
      }
      list[i].NRR=NRR;
      i++;
      if(i%20==0){
        list=(PK*)realloc(list,(i+20)*sizeof(PK));
      }
      fread(&n,1,4,SKlist);
    }
    (*nSK)=i;
    return list;
  }
